package DataStr.homework04.h2;

public class binarySearch {
    public static int binarySearch(int[]arr,int target){
        int left=0;
        int right=arr.length-1;
        int count=0;//对比次数
        while(left<=right){
            count++;
            int mid=left+(right-left)/2;
            if(arr[mid]==target){
                return count;
            }else if(arr[mid]>target){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
        return -1;
    }
    public static void main(String[]args){
        int[] arr = {5, 11, 23, 35, 51, 64, 72, 85, 88, 90, 98};
        System.out.println("二分查找");
        int target30=30;
        int target72=72;
        int count30=binarySearch(arr,target30);
        if(count30==-1){
            System.out.println("查找目标 " + target30 + " 的查找结果: 未找到");
        }else{
            System.out.println("查找目标 " + target30 + " 的查找结果: 找到");
        }
        int count72=binarySearch(arr,target72);
        if(count72==-1){
            System.out.println("查找目标 " + target72 + " 的查找结果: 未找到");
        }else{
            System.out.println("查找目标 " + target72 + " 的查找结果: 找到");
        }
    }
}
